var parentId;
var rightClickId;
var renameParentId;

function breadcrumb(name, parentId){
    if(parentId != null){
        var breadcrumb = $('.breadcrumb');
        removeElementAndSiblings("breadcrumb-"+parentId);
        breadcrumb.append("<li class=\"breadcrumb-item active text-\" id='breadcrumb-"+parentId+"' aria-current=\"page\" onclick='drawFile(\""+name+"\","+parentId+")'>"+name+"</li>\n")
    }else{
        var breadcrumb = $('.breadcrumb');
        removeElementAndSiblings("breadcrumb-0");
        breadcrumb.append("<li class=\"breadcrumb-item active text-\" id='breadcrumb-0' aria-current=\"page\">"+name+"</li>\n")
    }
}

function drawFile(name, parentId){
    this.parentId = parentId;
    hideUploadModalBtn(parentId);
    if(name != null) {
        breadcrumb(name, parentId);
    }
    var jsonObj = {"parentId":parentId}
    var result=httpPost(baseUrl+"/file/fileList",jsonObj);
    var fileList = $('#fileList');
    fileList.empty();
    if(result.flag==1){
        if(result.result.length==0){
            fileList.html("<div class=\"vertical-center folder-warning\">" +
                "<h1>该文件夹为空</h1>" +
                "</div>")
        }
        for (var i=0;i<result.result.length;i++){
            if(result.result[i].fileType==0){
                fileList.append("<a class=\"btn btn-app mt-2 btn-file\" title='文件名："+result.result[i].fileName+"' onclick='drawFile(\""+result.result[i].fileName+"\","+result.result[i].id+")'>" +
                    fileIcon(result.result[i].fileType) +
                    "<span hidden='hidden'>"+result.result[i].id+"</span>"+
                    result.result[i].fileName+"</a>\n")
            }else{
                fileList.append("<a class=\"btn btn-app mt-2 btn-file\" title='文件名："+result.result[i].fileName+"' onclick='fileDetail("+result.result[i].id+")'>" +
                    fileIcon(result.result[i].fileType) +
                    "<span hidden='hidden'>"+result.result[i].id+"</span>"+
                    result.result[i].fileName+"</a>\n")
            }

        }
    }else{
        toastr.error("错误",result.msg);
    }
    popupRC();
}

$("#searchBtn").click(function (){
    var keyword = $("#search").val()
    if(keyword == ""){
        drawFile("我的文件",0);
    }else{
        breadcrumb("我的搜索", null);
        var jsonObj = {"keyword":keyword}
        var result=httpPost(baseUrl+"/file/searchFile",jsonObj);
        var fileList = $('#fileList');
        fileList.empty();
        if(result.flag==1){
            for (var i=0;i<result.result.length;i++){
                if(result.result[i].fileType==0){
                    fileList.append("<a class=\"btn btn-app mt-2 btn-file file-div\" title="+result.result[i].filename+" onclick='drawFile(\""+result.result[i].fileName+"\","+result.result[i].id+")'>" +
                        fileIcon(result.result[i].fileType) +
                        "<span hidden='hidden'>"+result.result[i].id+"</span>"+
                        result.result[i].fileName+"</a>\n")
                }else{
                    fileList.append("<a class=\"btn btn-app mt-2 btn-file file-div\" title="+result.result[i].filename+" onclick='fileDetail("+result.result[i].id+")'>" +
                        fileIcon(result.result[i].fileType) +
                        "<span hidden='hidden'>"+result.result[i].id+"</span>"+
                        result.result[i].fileName+"</a>\n")
                }

            }
        }else{
            toastr.error("错误",result.msg);
        }
        popupRC();
    }
});

function fileIcon(type){
    switch (type) {
        case 0:
            return "<i class=\"fa fa-folder-open\"></i>";
        case 1:
            return "<i class=\"fa fa-image\"></i>";
        case 2:
            return  "<i class=\"fa fa-video-camera\"></i>";
        case 3:
            return  "<i class=\"fa fa-file-zip-o\"></i>";
        case 5:
            return  "<i class=\"fa fa-volume-up\"></i>";
        case 6:
            return  "<i class=\"fa fa-file-text-o\"></i>";
        default:
            return  "<i class=\"fa fa-file\"></i>";
    }
}

function newFolder(){
    $("#folderName").val('');
    $("#newFolderModal").modal('show');
}

$("#createFolderBtn").click(function (){
    var folderName = $("#folderName").val();
    var jsonObj = {
        "fileName": folderName,
        "fileType": 0,
        "fileSize": 0,
        "parentId": parentId,
        "fileUrl":"",
    }
    var result=httpPost(baseUrl+"/file/createFile",jsonObj);
    if(result.flag==1){
        $("#newFolderModal").modal('hide');
        drawFile(folderName,result.result);
    }else{
        toastr.error("错误",result.msg);
    }
});

function hideUploadModalBtn(parentId){
    if (parentId==0){
        $("#uploadModalBtn").slideUp('fast');
        $("#uploadModalBtn2").slideUp('fast');
    }else{
        $("#uploadModalBtn").slideDown('fast');
        $("#uploadModalBtn2").slideDown('fast');

    }
}

function editFileNameModal(){
    var jsonObj = {
        "id": rightClickId
    }
    var result=httpPost(baseUrl+"/file/fileDetail",jsonObj);
    if(result.flag==1){
        renameParentId = result.result.parentId
        $("#editFolderName").val(result.result.fileName)
        $("#editFileModal").modal('show');
        setTimeout(function() {
            $("#editFolderName").select();
        }, 500);
    }else{
        toastr.error("错误",result.msg);
    }
}

$("#editFileBtn").click(function (){
    var name = $("#editFolderName").val();
    var jsonObj = {
        "id": rightClickId,
        "parentId": renameParentId,
        "name": name
    }
    var result=httpPost(baseUrl+"/file/fileRename",jsonObj);
    if(result.flag==1){
        $("#editFileModal").modal('hide');
        drawFile(null, renameParentId);
    }else{
        toastr.error("错误",result.msg);
    }
});


function deleteFileModal(){
    var jsonObj = {
        "id": rightClickId
    }
    var result=httpPost(baseUrl+"/file/fileDetail",jsonObj);
    if(result.flag==1){
        renameParentId = result.result.parentId;
    }else{
        toastr.error("错误",result.msg);
    }
    $("#deleteFileModal").modal('show');
}

$("#deleteFileBtn").click(function () {
    var jsonObj = {
        "id": rightClickId
    }
    var result=httpPost(baseUrl+"/file/deleteFile",jsonObj);
    if(result.flag==1){
        $("#deleteFileModal").modal('hide');
        drawFile(null, renameParentId);
    }else{
        toastr.error("错误",result.msg);
    }
});

var progressId=0;
document.querySelector("#fileInput").onchange = async function () {
    if (document.querySelector("#fileInput").files.length != 0) {
        const fileInput = event.target.files[0];
        progressId++;
        var file = new FormData(document.getElementById("form-uploadFile"));
        var jsonData = {
            "parentId": parentId
        };
        const fileHash = await getFileHash(fileInput);
        file.set("parentId", parentId);
        file.set("fileHash", fileHash);
        const fileField = file.get('logFile');
        const fileName = fileField.name;
        $(".dropdown-list-content").prepend("<a href=\"#\" class=\"dropdown-item\">\n" +
            "<i class=\"fe fe-upload\"></i>\n" +
            "<div class=\"dropdown-item-desc\">\n" +
            "<b>" + fileName + "</b>\n" +
            "</div>" +
            "<div class=\"dropdown-item-desc\">\n" +
            "<div id=\"fileProgress-" + progressId + "\" class=\"progress-short\"></div>\n\n" +
            "</div>\n" +
            "</a>")
        $("#notification").addClass("beep");
        uploadFile(baseUrl + "/resource/uploadFile", file, "#fileProgress-" + progressId, (data) => {
            var result = JSON.parse(data);
            if (result.flag == 1) {
                drawFile(null, parentId);
            } else {
                toastr.error("错误", result.msg);
            }
            $('#fileInput').val(''); //处理完之后只需要加这个代码即可
        });
    }
}

function dowloadFile(){
    var jsonObj = {
        "id": rightClickId,
        "isOnline":0
    }
    var result=httpPost(baseUrl+"/file/fileDetail",jsonObj);
    if(result.flag==1){
        const fileName = result.result.fileName; // 文件名
        const fileUrl = baseUrl+'/resource/downloadFile'; // 文件的下载链接
        fetchFile(fileUrl, jsonObj, (blob) => {
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = fileName;
            link.target = '_blank';
            link.style.display = 'none';

            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        });
    }else{
        toastr.error("错误",result.msg);
    }
}

function fileDetail(id){
    var jsonObj = {
        "id": id,
        "isOnline":1
    }
    var result=httpPost(baseUrl+"/file/fileDetail",jsonObj);
    if(result.flag==1){
        if (result.result.fileType == 1 || result.result.fileType == 2||
            result.result.fileType == 5 || result.result.fileType == 6) {
            $("#onlineFileModal").modal('show')
            fetchFile(baseUrl + "/resource/downloadFile", jsonObj, (blob) => {
               switch (result.result.fileType){
                   case 1:
                       const imgUrl = URL.createObjectURL(blob);
                       const img = document.createElement('img');
                       img.src = imgUrl;
                       img.style.width = '100%';
                       $("#resourceArea").html(img);
                       break;
                   case 2:
                       const videoUrl = URL.createObjectURL(blob);
                       const video = document.createElement('video');
                       video.setAttribute('controls', 'true');
                       video.src = videoUrl;
                       video.style.width = '100%';
                       $("#resourceArea").html(video);
                       break;
                   case 5:
                       const audioUrl = URL.createObjectURL(blob);
                       const audio = document.createElement('audio');
                       audio.setAttribute('controls', 'true');
                       audio.src = audioUrl;
                       audio.style.width = '100%';
                       $("#resourceArea").html(audio);
                       break;
                   case 6:
                       const reader = new FileReader();
                       reader.onload = function(event) {
                           const text = event.target.result;
                           $("#resourceArea").text(text).css('word-wrap', 'break-word');
                       };
                       reader.readAsText(blob);
               }
            });
        }
    }else{
        toastr.error("错误",result.msg);
    }
}

function fileDetailModal(){
    var jsonObj = {
        "id": rightClickId,
    }
    var result=httpPost(baseUrl+"/file/fileDetail",jsonObj);
    if(result.flag==1){
        $("#fileDetailModal").modal('show');
        $("#fileTypeDetail").html(fileTypeName(result.result.fileType));
        $("#userNameDetail").html(result.result.userName);
        $("#isPrivateDetail").html(isPrivateText(result.result.isPrivate));
        $("#fileSizeDetail").html(result.result.fileSize/1000+"KB");
        $("#lastTimeDetail").html(result.result.lastTime);
    }
}

function isPrivateText(isPrivate){
    switch (isPrivate) {
        case 0:
            return "公开";
        case 1:
            return  "私有";
    }
}
function fileTypeName(type){
    switch (type) {
        case 0:
            return "文件夹";
        case 1:
            return "图片";
        case 2:
            return  "视频";
        case 3:
            return  "压缩包";
        case 5:
            return  "音频";
        case 6:
            return  "文档";
        case 4:
            return  "其他文件";
    }
}

function popupRC(){
    $(".btn-file").bind('contextmenu', function (e) {
        e.preventDefault(); // prevents native menu from being shown
        $("#popupRC").css({ position: "absolute", top: e.pageY,
            left: e.pageX, display: "block" });
        var clickedElement = e.currentTarget;
        var spanElement = clickedElement.querySelector('span');

        // 对点击的元素进行操作
        rightClickId = spanElement.textContent;
        //判断是否隐藏下载按钮
        var jsonObj = {
            "id": rightClickId
        }
        var result=httpPost(baseUrl+"/file/fileDetail",jsonObj);
        if(result.flag==1){
            if(result.result.fileType==0){
                $("#dowloadFileBtn").hide();
            }else{
                $("#dowloadFileBtn").show();
            }
        }
    });
}